package com.example.jasonrpc.example;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * 基于RMI的RPC实现服务端
 */
public class RMIServer {
    public static void main(String[] args) {
        String serverIp = ConfigUtil.getServerIp("config");
        int serverPort = ConfigUtil.getServerPort("config");
        //rmiLocalServerTest();
        rmiRemoteServerTest(serverIp, serverPort);
    }

    private static void rmiRemoteServerTest(String serverIp, int serverPort) {
        try {
            Registry registry = LocateRegistry.createRegistry(serverPort);
            CalcService calcService = new CalcServiceImpl();
            Naming.rebind("//"+serverIp+":"+serverPort+"/CalcService", calcService);
            System.out.println("RMI server start");
        } catch (RemoteException | MalformedURLException e) {
            e.printStackTrace();
        }
    }

    private static void rmiLocalServerTest(int serverPort) {
        try {
            Registry registry = LocateRegistry.createRegistry(serverPort);
            CalcService calcService = new CalcServiceImpl();
            registry.rebind("CalcService", calcService);
            System.out.println("RMI server start");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
